<template>
  <div>
    <a-modal
      centered
      :title="title"
      :width="1200"
      :confirmLoading="confirmLoading"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <a-spin :spinning="confirmLoading">
<!--      <a-form :form="form" v-if='formVisible'>-->
<!--        <a-form-item-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          label="区域名称"-->
<!--          :hidden="false"-->
<!--          hasFeedback >-->
<!--          <a-input id="areaName" placeholder="请输入区域名称" v-decorator="['areaName', validatorRules.name ]"/>-->
<!--        </a-form-item>-->

<!--        <a-form-item-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          label="备注"-->
<!--          :hidden="false"-->
<!--          hasFeedback >-->
<!--          <a-input placeholder="请输入备注" v-decorator="['remark']"/>-->
<!--        </a-form-item>-->
<!--      </a-form>-->
      <a-form layout="inline">
      <!-- 查询区域 -->
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="项目名称">
                <a-input style='width: 200px'  placeholder="请输入项目名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
            <a-form-item label="项目编号">
              <a-input placeholder="请输入项目编号" v-model="queryParam.projectNum"></a-input>
            </a-form-item>
          </a-col>
            <a-col :span="8">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button
                  type="primary"
                  @click="searchReset"
                  icon="reload"
                  style="margin-left: 8px"
                >重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>

      <!-- table区域-begin -->
      <div>
        <a-table
          size="small"
          bordered
          rowKey="id"
          :columns="columns1"
          :dataSource="dataSource1"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{ y: 240 }"
          :rowSelection="{selectedRowKeys: selectedRowKeys,onSelectAll:onSelectAll,onSelect:onSelect,onChange: onSelectChange}"
          @change="handleTableChange"
        ></a-table>
      </div>
      </a-spin>
      <!-- table区域-end -->
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { getAction,postAction } from '@/api/manage'
import { duplicateCheck } from '@api/api'
import pick from 'lodash.pick'

export default {
  name: 'SelectProject',
  data() {
    return {
      title: '添加项目区域以及绑定项目',
      parentId:"",
      names: [],
      confirmLoading: false,
      formVisible:true,
      //区域id
      areaId:"",
      visible: false,
      placement: 'right',
      description: '',
      // 查询条件
      queryParam: {},
      // 表头
      columns1: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '项目编号',
          align: 'center',
          width: 113,
          dataIndex: 'projectNum'
        },
        {
          title: '项目名称',
          align: 'center',
          width: 100,
          dataIndex: 'name'
        },
        {
          title: '状态',
          align: 'center',
          width: 100,
          customRender: x => ('1' == x ? '在用' : '停用'),
          dataIndex: 'status'
        }
      ],
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      validatorRules:{
        name: {
          rules: [{
            required: true, message: '请输入区域名称!'
          }, {
            validator: this.validateAreaName,
          }]
        },
      },
      //数据集
      dataSource1: [],
      dataSource2: [],
      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      model:{},
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      url: {
        noBindList: '/project/noBindList',
        bind: '/project/bind'
      }
    }
  },
  created() {
    this.initKeyUpEnter()
    this.loadData()
  },
  methods: {
    init() {
      this.queryParam = {}
      this.dataSource1 = []
      this.dataSource2 = []
      this.selectedRowKeys = []
      this.selectedRows = []
      this.searchReset()
    },
    searchQuery() {
      this.loadData(1)
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    handleCancel() {
      this.visible = false
    },
    validateAreaName(rule, value, callback) {
      var params = {
        tableName: 't_area',
        fieldName: 'name',
        fieldVal: value,
        dataId: this.areaId
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback("区域已存在!")
        }
      })
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.selectedRowKeys.length>0){
            that.confirmLoading = true;
            this.dataSource2 = this.selectedRowKeys
            let formData = Object.assign(this.model, values);
            formData.projectIds = this.dataSource2
            formData.parentId = this.parentId
            console.log(formData)
            postAction(this.url.bind, formData).then((res) => {
              if(res.success){
                this.$message.success(res.message)
                this.visible=false
                this.$emit('ok')
                this.loadData()
              }else{
                this.$message.warning("系统内部错误")
              }
            })
          }else{
            this.$message.error("请选择至少一个项目")
          }

        }
        that.confirmLoading = false;
      })


      //子组件向父组件传值
      // this.$emit('selectFinished', this.dataSource2)
      //绑定项目


      this.visible = false
    },
    setAreaId(selectedKey){
      this.searchQuery()
      this.visible = true
      this.parentId = selectedKey
    },
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      getAction(this.url.noBindList, params).then(res => {
        if (res.success&&res.result!=null) {
          this.dataSource1 = res.result.records
          this.ipagination.total = res.result.total
        }
      })
    },
    getQueryParams() {
      var param = Object.assign({}, this.queryParam, this.isorter)

      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected === true) {
        for (var a = 0; a < changeRows.length; a++) {
          this.dataSource2.push(changeRows[a])
        }
      } else {
        for (var b = 0; b < changeRows.length; b++) {
          this.dataSource2.splice(this.dataSource2.indexOf(changeRows[b]), 1)
        }
      }
    },
    onSelect(record, selected) {
      if (selected === true) {
        this.dataSource2.push(record)
      } else {
        var index = this.dataSource2.indexOf(record)
        if (index >= 0) {
          this.dataSource2.splice(this.dataSource2.indexOf(record), 1)
        }
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectedRows
    },

    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      // console.log(sorter);
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    initKeyUpEnter() {
      var _this = this
      document.onkeydown = function(e) {
        let key = window.event.keyCode
        if (key == 13) {
          _this.loadData()
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px;
}

.ant-btn-danger {
  background-color: #ffffff;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}
</style>